/**
 * Created by KaiBo on 2016-12-14.
 */
(function($){

    $.fn.register = function(options){
        /*
         *属性
         * */
        /*
         *默认配置
         */
        var DefautlSetting = {
            openModal:$(".add-img"),
            __Root__:"",
            uploadUrl:"",
            deleteUrl:"",
            maxM:3,
            UpBtn: "up_img",
            DivShow: "imgdiv",
            ImgShow: "imgShow",
            Width: 100,
            Height: 100,
            ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
            ErrMsg: "选择文件错误,图片类型必须是(gif,jpeg,jpg,bmp,png)中的一种",
            callback: function () {
            }
        };

        /*
         *this(当前对象)
         */
        var _this = this;
        // 不管有没有传入参数，先合并再说；
        var params = $.extend({}, DefautlSetting, options || {});

        var maxsize = params.maxM*1024*1024;
        var errMsg = "上传的文件不能超过"+params.maxM+"M！！！";
        var tipMsg = "您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过"+params.maxM+"M，建议使用FireFox、Chrome浏览器。";
        var browserCfg = {};
        var ua = window.navigator.userAgent;
        if (ua.indexOf("MSIE")>=1){
            browserCfg.ie = true;
        }else if(ua.indexOf("Firefox")>=1){
            browserCfg.firefox = true;
        }else if(ua.indexOf("Chrome")>=1){
            browserCfg.chrome = true;
        }


        /**
         *
         * 初始化
         */
        _this.Init = function(){
            var html = '<div class="modal" id="uploadModal"  tabindex="-1" role="dialog" aria-labelledby="myModalLabel">';
            html += '       <div class="modal-dialog" role="document">';
            html += '           <div class="modal-content">';
            html += '               <div class="modal-header">';
            html += '                   <button type="button" class="close" data-dismiss="modal" aria-label="Close">';
            html += '                       <span aria-hidden="true">&times;</span>';
            html += '                   </button>';
            html += '                   <h4 class="modal-title">上传图片</h4>';
            html += '               </div>';
            html += '               <div class="modal-body">';
            html += '                   <div class="container-fluid">';
            html += '                       <div class="row">';
            html += '                           <div class="col-xs-12">';
            html += '                               <form id="uploadImg" action="" enctype="multipart/form-data">';
            html += '                                   <div class="form-group">';
            html += '                                       <label>选择图片</label>';
            html += '                                       <div id="imgdiv" style="margin: 10px 0">';
            html += '                                            <img id="imgShow" class="img-responsive" />';
            html += '                                       </div>';
            html += '                                       <input type="file" name="pic" id="up_img">';
            html += '                                       <p class="help-block">仅支持gif, jpeg, jpg, bmp, png格式</p>';
            html += '                                   </div>';
            html += '                               </form>';
            html += '                           </div>';
            html += '                       </div>';
            html += '                   </div>';
            html += '               </div>';
            html += '               <div class="modal-footer">';
            html += '                   <button type="button" class="btn btn-upload-ok btn-primary">上传</button>';
            html += '                   <button type="button" class="btn btn-upload-close btn-default" data-dismiss="modal">Close</button>';
            html += '               </div>';
            html += '           </div>';
            html += '       </div>';
            html += '  </div>';
            $("body").append(html);
        };
        /**
         * 判断图片大小
         */
        _this.checkfile = function(){
            try{
                var obj_file = document.getElementById("up_img");
                if(obj_file.value==""){
                    alert("请先选择上传文件");
                    return false;
                }
                var filesize = 0;
                if(browserCfg.firefox || browserCfg.chrome ){
                    filesize = obj_file.files[0].size;
                }else if(browserCfg.ie){
                    var obj_img = document.getElementById('imgShow');
                    obj_img.dynsrc=obj_file.value;
                    filesize = obj_img.fileSize;
                }else{
                    console.log(tipMsg);
                    return true;
                }
                if(filesize==-1){
                    console.log(tipMsg);
                    return true;
                }else if(filesize > maxsize){
                    alert(errMsg);
                    return false;
                }else{
                    return true;
                }
            }catch(e){
                alert(e);
            }
        };
        /*
         *判断为null或者空值
         */
        _this.IsNull = function (value) {
            if (typeof (value) == "function") {
                return false;
            }
            if (value == undefined || value == null || value == "" || value.length == 0) {
                return true;
            }
            return false;
        };
        /*
         *读取配置
         */
        var Setting = {
            UpBtn: _this.IsNull(options.UpBtn) ? params.UpBtn : options.UpBtn,
            DivShow: _this.IsNull(options.DivShow) ? params.DivShow : options.DivShow,
            ImgShow: _this.IsNull(options.ImgShow) ? params.ImgShow : options.ImgShow,
            Width: _this.IsNull(options.Width) ? params.Width : options.Width,
            Height: _this.IsNull(options.Height) ? params.Height : options.Height,
            ImgType: _this.IsNull(options.ImgType) ? params.ImgType : options.ImgType,
            ErrMsg: _this.IsNull(options.ErrMsg) ? params.ErrMsg : options.ErrMsg,
            callback: _this.IsNull(options.callback) ? params.callback : options.callback
        };
        /*
         *获取文本控件URL
         */
        _this.getObjectURL = function (file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        };
        /*
         *绑定事件
         */
        _this.Bind = function () {
            document.getElementById(Setting.UpBtn).onchange = function () {
                if (this.value) {
                    if (!RegExp("\.(" + Setting.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
                        alert(Setting.ErrMsg);
                        this.value = "";
                        return false;
                    }
                    if (navigator.userAgent.indexOf("MSIE") > -1) {
                        try {
                            document.getElementById(Setting.ImgShow).src = _this.getObjectURL(this.files[0]);
                        } catch (e) {
                            var div = document.getElementById(Setting.DivShow);
                            this.select();
                            top.parent.document.body.focus();
                            var src = document.selection.createRange().text;
                            document.selection.empty();
                            document.getElementById(Setting.ImgShow).style.display = "none";
                            div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                            div.style.width = Setting.Width + "px";
                            div.style.height = Setting.Height + "px";
                            div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
                        }
                    } else {
                        document.getElementById(Setting.ImgShow).src = _this.getObjectURL(this.files[0]);
                    }
                    Setting.callback();
                }
            }
        };
        /*
         *上传成功返回事件
         */
        _this.setImg = function(imgUrl,unid){
            var $addImg = $(".add-img");
            $addImg.parent(".img-list").prev("input").val(unid);
            var len = $(".img-item").length;
            imgUrl = params.__Root__+imgUrl;
            if(len < 1){
                var html = ' <div class="img-item" style="background-image: url('+imgUrl+')">';
                html += '       <span class="glyphicon delete-img glyphicon-remove-circle"></span>';
                html += '   </div>';
                $addImg.before(html);
            }else{
                $addImg.prev(".img-item").prop("background-image","url("+imgUrl+")");
            }
            $addImg.hide();
        };



        //上传图片
        $(document).on("click",".btn-upload-ok",function () {
            if(!_this.checkfile())return;
            var options = {
                type: 'post',
                url: params.uploadUrl,
                dataType: 'text',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var json_obj = JSON.parse(data);
                    if(json_obj.status=='no'){
                        alert('上传的图片不能大于'+params.maxM+'MB！');
                        return;
                    }
                    var imgUrl = json_obj.path;
                    var unid = json_obj.path;
                    _this.setImg(imgUrl,unid);
                    $("#uploadModal").modal("hide");
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    alert("网络连接失败！");
                }
            };
            $("#uploadImg").ajaxSubmit(options);
        });

        //删除图片
        $(document).on("click", ".delete-img", function () {
            var $elem = $(this);
            $elem.parents(".img-list").prev("input").val("");
            $elem.parent(".img-item").remove();
            $(".add-img").show();
        });

        //打开弹窗
        $(params.openModal).click(function(){
            $("#uploadModal").modal();
        });

        //类型点击
        $(document).on("click", ".car-type", function () {
            var $elem =  $(this);
            $elem.siblings(".car-type").removeClass("active");
            $elem.addClass("active");
            $elem.parent().prev("input").val($elem.attr("data-val"));
        });

        //执行
        _this.Init();
        _this.Bind();
    }


})(jQuery);